<?php

/**
 * 用户服务 - RPC
 * 
 * @author birdy <freebirdy@foxmail.com>
 */

namespace app\member\rpc;

use think\Db;

class Member extends \app\common\rpc\Rpc
{

    /**
     * 登录处理
     * 
     * @param type $account  账号（手机号或者供应商账号）
     * @param type $password 密码明文
     * 
     * return Member[]
     */
    public function login($account, $password, $ip = null)
    {
        //手机号
        $ishr = config('login_use_api') ? true : false;
        $is_phone = false;
        if (preg_match("/^13[0-9]{9}$|14[0-9]{9}|15[0-9]{9}$|18[0-9]{9}|17[0-9]{9}$/", $account)) {
            // To do 用户体系对接
            $is_phone = true;
        }

        $member = [];
        if ($ishr && $is_phone) {
            $info = $this->hr_login($account, $password);
            if ($info['info']) {
                $map = [
                    'mobile' => $info['info']['phone']
                ];
                $member = Db::name("member")->where($map)->find();
                if (!$member) {
                    //添加一个新用户
                    $register_info = [];
                    $register_info['name'] = $info['info']['name'];
                    $register_info['passwd'] = md5($password);
                    $register_info['mobile'] = $info['info']['phone'];
                    $register_info['company'] = $info['info']['firmName'] ?: "未设置";
                    $register_info['email'] = $info['info']['email'] ?: null;
                    $register_info['mobile_bind'] = 1;
                    $register_info['register_time'] = time();
                    $register_info['last_login_time'] = time();
                    $register_info['last_login_ip'] = $ip;
                    $register_info['status'] = 1;
                    $register_info['email_bind'] = $info['info']['email'] ? 1 : 0;

                    $id = Db::name('member')->insert($register_info, false, true);
                    if ($id > 0) {
                        $register_info['id'] = $id;
                        $member = $register_info;
                    } else {
                        return '登录失败';
                    }
                } else {
                    $update = [];
                    $update['last_login_time'] = time();
                    $update['last_login_ip'] = $ip;
                    Db::name('member')->where('id=' . $member['id'])->update($update);

                    $map = ['member_id' => $member['id']];
                    $store = Db::name("store")->where($map)->find();

                    $map = [
                        'seller_name' => $store['seller_name'],
                        'is_admin' => 1
                    ];
                    $seller = Db::name('seller')->where($map)->find();
                    if ($seller) {
                        $store['seller_id'] = $seller['seller_id'];
                        $store['is_admin'] = 1;
                        $member['store'] = $store;
                    }
                }
            } else {
                return $info['msg'] ?: '账号或者密码错误';
            }
        } else {
            $password = md5($password);
            if ($is_phone) {
                $map = [
                    'mobile' => $account,
                    'passwd' => $password
                ];
                $member = Db::name("member")->where($map)->find();
                if (!$member) {
                    return false;
                } else {
                    $update = [];
                    $update['last_login_time'] = time();
                    $update['last_login_ip'] = $ip;
                    Db::name('member')->where('id=' . $member['id'])->update($update);

                    $map = ['member_id' => $member['id']];
                    $store = Db::name("store")->where($map)->find();

                    $map = [
                        'seller_name' => $store['seller_name'],
                        'is_admin' => 1
                    ];
                    $seller = Db::name('seller')->where($map)->find();
                    if ($seller) {
                        $store['seller_id'] = $seller['seller_id'];
                        $store['is_admin'] = 1;
                        $member['store'] = $store;
                    }
                }
            } else {
                $map = [
                    'seller_name' => $account,
                    'is_admin' => 1
                ];
                $seller = Db::name('seller')->where($map)->find();

                if (!$seller || $seller['member_id'] < 1) {
                    return false;
                }
                $member = Db::name('member')->find($seller['member_id']);
                if (!$member || $password !== $member['passwd']) {
                    return false;
                } else {
                    $update = [];
                    $update['last_login_time'] = time();
                    $update['last_login_ip'] = $ip;
                    Db::name('member')->where('id=' . $seller['member_id'])->update($update);
                }

                $store = Db::name("store")->find($seller['store_id']);

                $store['seller_id'] = $seller['seller_id'];
                $store['is_admin'] = 1;
                $member['store'] = $store;
            }
        }

        return $member;
    }

    /**
     * 社保ＨＲ登录
     * @param type $phone
     * @param type $password
     * @return type
     */
    private function hr_login($phone, $password)
    {
        $api = config('ucenter.url') ?: 'https://web.aiyuangong.com';
        $url = $api . "/sso/oauth2.0/accessToken";

        $paras = [
            'grant_type' => 'password',
            'client_id' => config('ucenter.id'),
            'username' => $phone,
            'password' => $password,
            'sourceType' => 'ehr',
            'credentialType' => 'password',
            'loginFromType' => 'server',
            'loginLocation' => 'ehr_web'
        ];

        $str = $this->http_request($url, $paras);
        $return = [];
        if ($str) {
            parse_str($str, $return);
            $return['info'] = $this->get_user_info($return['access_token']);
        }
        return $return;
    }

    //获取SSO单点登录跳转地址
    public function get_sso_url($account, $url)
    {
        $api = config('ucenter.url') ?: 'https://web.aiyuangong.com';
        $token = $this->get_access_token($account);
        if ($token) {
            return $api . "/hrm/login/oauth?access_token=" . $token . "&return_url=" . urlencode($url);
        } else {
            return $url;
        }
    }

    //获取Access Token
    public function get_access_token($account)
    {
        $api = config('ucenter.url') ?: 'https://web.aiyuangong.com';
        $url = $api . "/sso/oauth2.0/accessToken";

        $paras = [
            'grant_type' => 'password',
            'client_id' => config('ucenter.id'),
            'username' => $account,
            'password' => config('ucenter.key'),
            'sourceType' => 'ehr',
            'credentialType' => 'trusted',
            'loginFromType' => 'server',
            'loginLocation' => 'ehr_web'
        ];

        $str = $this->http_request($url, $paras);
        $return = [];
        if ($str) {
            parse_str($str, $return);
            if (isset($return['access_token'])) {
                return $return['access_token'];
            }
        }

        return false;
    }

    //获取用户信息
    public function get_user_info($token)
    {
        $api = config('ucenter.url') ?: 'https://web.aiyuangong.com';
        $url = $api . "/sso/oauth2.0/profile";

        $rs = $this->http_request($url, [], ['Authorization: Bearer ' . $token]);
        if ($rs) {
            $rs = json_decode($rs, 'true');
            return [
                'phone' => $rs['attributes']['mobilePhone'],
                'name' => $rs['attributes']['name']
            ];
        }
        return false;
    }

    /**
     * http请求，支持GET和POST
     * 传入data对象则使用post传输
     * 传入timeout 则启用超时设置
     * 传入head 为true值 则返回响应头数据
     * 传入iscookie,则存cookie进/shop/cookie文件夹
     */
    private function http_request($url, $data = null, $header = [])
    {
        //初始化curl
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        $ssl = false;
        if (substr($url, 0, 5) === 'https') {
            $ssl = 2;
        }

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $ssl);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, $ssl);

        if ($data) {
            $data = is_array($data) ? http_build_query($data) : $data;
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }

        $header [] = 'Connection: keep-alive';
        $header [] = 'User-Agent: ozilla/5.0 (X11; Linux i686) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.186 Safari/535.1';
        $header [] = 'Accept:application/json,text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8';
        $header [] = 'Accept-Language: zh-CN,zh;q=0.8';
        $header [] = 'Accept-Charset: utf-8;q=0.7,*;q=0.3';
        $header [] = 'Cache-Control:max-age=0';
        $header [] = 'Content-Type:application/x-www-form-urlencoded';

        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

        $res = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if ($httpCode == 200) {
            return $res;
        } else {
            return false;
        }
    }

}
